package com.ylcode.libback.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylcode.libback.mapper.BookMapper;
import com.ylcode.libback.model.pojo.Book;
import com.ylcode.libback.model.pojo.Employee;
import com.ylcode.libback.model.pojo.Record;
import com.ylcode.libback.model.pojo.User;
import com.ylcode.libback.service.BookService;
import com.ylcode.libback.service.EmployeeService;
import com.ylcode.libback.service.RecordService;
import com.ylcode.libback.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Resource
    private EmployeeService employeeService;

    @Resource
    private RecordService recordService;

    @Override
    public List<Book> selectByBookNameOrAuthor(String param) {
        LambdaQueryWrapper<Book> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Book::getBookName, param);
        List<Book> books = this.list(lambdaQueryWrapper);
        if (books.size() == 0) {
            lambdaQueryWrapper.eq(Book::getBookAuthor, param);
            books = this.list();
        }
        if (books.size() != 0) {
            return books;
        }
        return null;
    }

    @Override
    public Boolean lend(Long bookId, Long userId) {
        Book book = this.getById(bookId);
        Employee employee = employeeService.getById(userId);
        book.setBookStatus("1");        //设置已被借阅
        book.setBookBorrower(employee.getName());//设置借阅人
        book.setBookBorrowTime(LocalDateTime.now());
        book.setBookReturnTime(LocalDateTime.now().plusDays(60));
        Record record = new Record();
        record.setRecordBookId(book.getBookId());
        record.setRecordBookIsbn(book.getBookIsbn());
        record.setRecordBookAuthor(book.getBookAuthor());
        record.setRecordBookName(book.getBookName());
        record.setRecordBookPress(book.getBookPress());
        record.setRecordBorrower(book.getBookBorrower());
        record.setRecordBookStatus(book.getBookStatus());
        record.setRecordBorrowTime(book.getBookBorrowTime());
        record.setRecordReturnTime(book.getBookReturnTime());
        boolean flag = recordService.save(record);
        if (!flag) {
            return false;
        }
        return this.updateById(book);
    }
}
